/**
 * @ author: 汪孟苹
 */
define(["jquery", 'bootstrap', "bbcare", "dm/vm/editMissionData",
	"scprit/followup/app/question/question.servers.js",
	"scprit/followup/app/question/question.ui.js"],
	function ($, bootstrap, $bb, $editMissionData,$questionServers, $questionUi) {
    var editMission = {};
    var URL = $bb.baseUrl("department");
    editMission.init = function(){
    	var templateId,missionId;	// 模板id
		var obj=$bb.getPageParams();
		if(obj.missionId){
			missionId=obj.missionId;
		}else if(obj.templateId){
			templateId=obj.templateId;
		}
    	if(templateId){
	    	$bb.ajax({
				url: URL + "followup/service/education/template/detail",
				data:JSON.stringify({
					data : {
						templateId: templateId
					}
				}),
				success: function(data){
					missionInfo($editMissionData.init,$editMissionData.ruleContentInit,data.data,0);
					if(data.success){
						$questionUi.init({
				        	id: "editMissionQuestion",
				            list: JSON.parse(data.data.templateParam),	  // 问卷
				            values: JSON.parse(data.data.paramValue),	// 问卷答案
				        });
				        $("#previewBox").html(data.data.templateContent);
						var topbars = [
							{
								"icon":"fa fa-floppy-o",
								"name":"保存",
								"callback":saveMission,
								"params":{"templateId":templateId,"missionId":missionId}
							}
						];
						$bb.toolbar(topbars);
						var objArr = $("#editMissionQuestion .qaCard input[name], #editMissionQuestion .qaCard select[name], #editMissionQuestion .qaCard textarea[name]");
				    	previewFun(objArr);
				    }
				}
			});
		}
		if(missionId){
			$bb.ajax({
				url: URL + "followup/service/education/detail",
				data:JSON.stringify({
					data : {
						contentId: missionId
					}
				}),
				success: function(data){
					if(data.success){
						var dataInfo = data.data;
						missionInfo($editMissionData.init,$editMissionData.ruleContentInit,dataInfo,1);
						$questionUi.init({
				        	id: "editMissionQuestion",
				            list: JSON.parse(data.data.templateParam),	  // 问卷
				            values: JSON.parse(data.data.templateValue),	// 问卷答案
				        });
				        $("#previewBox").html(data.data.content);
				        templateId = data.data.templateId;
				        var topbars = [
							{
								"icon":"fa fa-floppy-o",
								"name":"保存",
								"callback":saveMission,
								"params":{"templateId":templateId,"missionId":missionId}
							}
						];
						$bb.toolbar(topbars);
						var objArr = $("#editMissionQuestion .qaCard input[name], #editMissionQuestion .qaCard select[name], #editMissionQuestion .qaCard textarea[name]");
				    	previewFun(objArr);
				    }
				}
			});
		}
    };
    function missionInfo(callback,callback2,dataInfo,num){
    	$bb.ajax({
			url: URL + "followup/service/education/educationPushType/list",
			success: function(data){
				if(data.success){
					var options = {
			        	id: "editMissionInfo",
			        	list: data.data,
					};
					var options2 = {
			        	id: "missionRuleContent",
			        	list: data.data,
					};
					if(num == 0){
						dataInfo = {
							title: dataInfo.templateName,
							bannelUrl: dataInfo.picture,
						};
					}
					options = $.extend(options,{dataInfo:dataInfo});
					options2 = $.extend(options2,{dataInfo:dataInfo});
					// console.log("bbbbbbbbbbbbbbbbbbbb",dataInfo)
					callback(options);
					callback2(options2);
					$("#missionPushRule").change(function(){
						var type = $(this).val();
						dataInfo = $.extend(dataInfo,{type: type});
			        	$editMissionData.ruleContentInit({
			        		id: "missionRuleContent",
			        		dataInfo: dataInfo
			        	});
					});
			        $("#missionLogoUrl").change(function(){
			        	addFile(this);
					});
				}
			}
		});
    }
    function addFile(obj){
    	var file = obj.files[0]
		var typeStr = "image/jpg, image/png, image/gif, image/jpeg";
	 	$("#missionLogo").attr("src",window.URL.createObjectURL(file));
	    if(typeStr.indexOf(file.type) >= 0){
	      	if (file.size > 20971520000) {
	            $bb.toastShow("上传的文件不能大于200M！");
	         	return;
	        }else{
	 	　		upload(obj,URL + "followup/img/save",file);
	　　　   }
	   	}else{
	        $bb.toastShow("请上传格式为jpg、png、gif、jpeg的图片！");
	    }
    }
    function upload(obj,url,file) {
        var fd = new FormData();
        fd.append("file", file);//上传的文件： 键名，键值
        $bb.ajax({
		  	url: url,
		  	processData: false,  // 告诉jQuery不要去处理发送的数据
		  	contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
		  	data: fd,
			success: function(data){
				if(data.success){
					$(obj).attr("logourl",data.data.imgUrl);
				}else{
					$bb.toastShow(data.msg ? data.msg :"上传图片失败！");
				}
			}
		});
    };
    function saveMissionParam(templateId,missionId){
    	var domId = $("#editMissionQuestion form").attr("id");
    	var values = $questionServers.getDataForDom(domId);
    	var mission = $editMissionData.getDataMission("editMissionInfo");
		var	content = $("#previewBox").html();
		var param = {
			templateId: templateId,
			content: content,
			templateValue: values,
		};
		param = $.extend(mission,param);
		var param2 = $.extend({id: missionId,},param);
		if (missionId) {
			return param2;
		}else{
			return param;
		}
    };
    var ajaxSaveMission = function(param){
		// console.log("aaaaaaaaaaaaa",param)
    	$bb.ajax({
			url: URL + "followup/service/education/modify",
			data:JSON.stringify({
				data : param
			}),
			success: function(data){
				if(data.success){
					$bb.toastShow("保存成功！");
					$bb.openPage("missionManagement");
				}else{
					$bb.toastShow(data.msg ? data.msg :"保存失败！");
				}
			}
		});
    }
    function validateMission(param,callback){
    	var reg1 = /^\d+$/;
    	var reg2 = /\S/;
    	if( !reg2.test(param.priority) ){
    		$bb.toastShow("宣教权重不可为空！");
    	}else if( !reg1.test(param.priority) ){
    		$bb.toastShow("宣教权重请输入数字（数字越小，权重越大）！");
		}else{
			callback(param);
		}
    }
    function saveMission(){
    	var params = $(this).data("params");
    	var param = saveMissionParam(params.templateId,params.missionId);
    	validateMission(param,ajaxSaveMission);
    }
    function previewFun(objArr){
		objArr.each(function(i){
    		objArr.eq(i).bind("input propertychange",function(){
    			var name = $(this).attr("name");
    			var value = $(this).val();
    			$("#previewBox div[id = '" + name + "']").html(value);
    		});
    	});
	}

    return editMission;
});
